public class Knight {
    int N = 5;
    int[][] map = new int[N][N];    //一个8*8的棋盘
    int TOTALLSTEPS = N * N -1;    //一共可以用的步数
    int waysnumber = 0;             //统计方法数

    public Knight(int x, int y) {

        move(x, y, TOTALLSTEPS);
        printMap(map);
    }

    public boolean move(int x, int y, int steps) {  //x:横坐标 y:纵坐标 steps:剩余步数
        //判断是否越界
        if (x < 0 || x > N-1 || y < 0 || y > N-1)
            return false;   //已经越界
        //判断是否访问过
        if (map[x][y] != 0)
            return false;    //已经访问过
        //判断是否完成一次遍历
        if (steps == 0) {
            waysnumber++;
            return true;    //成功遍历一次
        }
        steps--;
        map[x][y] = TOTALLSTEPS - steps;    //标记走的顺序
        //对该坐标下的八个位置进行遍历
        if (move(x + 1,y + 2, steps) == true)
            return true;
        if (move(x + 1,y - 2, steps) == true)
            return true;
        if (move(x - 1,y + 2, steps) == true)
            return true;
        if (move(x - 1, y -2, steps) == true)
            return true;
        if (move(x + 2,y + 1, steps) == true)
            return true;
        if (move(x + 2,y - 1, steps) == true)
            return true;
        if (move(x - 2,y + 1, steps) == true)
            return true;
        if (move(x - 2,y - 1, steps) == true)
            return true;
        //以上八个方向都不可行
        map[x][y] = 0;
        return false;
    }

    /**
     * 打印出结果
     * @param map
     */
    public void printMap(int[][] map) {
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map[i].length; j++) {
                System.out.print(map[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("***********************");
    }
}
